<?php
namespace app\admin\controller;
use think\Request;
use think\Config;
use app\common\model\GoodsModel;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth;

class Upfile
{
	public function uploadimage(){
		$uploadFile = reset($_FILES);
		// var_dump( $_SERVICE );die();
		if(empty($uploadFile)){
			return json_encode([
				'msg' => '没有上传文件',
				'state' => 'ERROR'
			]);
		}

		$fileName = $uploadFile['name'];
		$fileSize = filesize($uploadFile['tmp_name']);
		$imageUrl = $this->upload($uploadFile);

		exit(json_encode([
			'originalName' => $fileName,
			'name' => $fileName,
			'url' => $imageUrl,
			'size' => $fileSize,
			'type' => '.jpg',
			'state' => 'SUCCESS'
		]));
	}

	private function upload($uploadFile){
    $upManager = new UploadManager();
    $qiniu = Config::get("qiniu");

    $auth = new Auth($qiniu['accessKey'], $qiniu['secretKey']);
    $token = $auth->uploadToken($qiniu['bucketName']);

    $key = md5(time().rand(0,99999).uniqid().rand(0,99999));
    $result = $upManager->putFile($token, $key, $uploadFile['tmp_name']);
    return $qiniu['domain']."/".$key;    
	}

	public function uploadOnlineImage($imageUrl){
		$upManager = new UploadManager();
		$qiniu = Config::get("qiniu");
		$auth = new Auth($qiniu['accessKey'], $qiniu['secretKey']);
		$token = $auth->uploadToken($qiniu['bucketName']);

		list($ret, $err) = $upManager->put($token, md5($imageUrl),file_get_contents($imageUrl) );

		if ($err !== null) {
			return json([
				'msg' => $err,
				'state' => 'ERROR'
			]);
		} else {
		  return $qiniu['domain']."/".md5($imageUrl);    
		}
	}
}